package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.domain.Dish;
import com.itheima.domain.Setmeal;
import com.itheima.domain.SetmealDish;
import com.itheima.dto.SetMealDto;
import com.itheima.excecption.CustomException;
import com.itheima.mapper.SetMealMapper;
import com.itheima.service.DishService;
import com.itheima.service.SetMealDishService;
import com.itheima.service.SetMealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper,Setmeal>
implements SetMealService{

    @Autowired
    DishService dService;

    @Autowired
    SetMealDishService sdService;


    @Override
    public List<Setmeal> getByIdList(Long id) {

        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();

        slqw.eq(Setmeal::getCategoryId,id);

        List<Setmeal> list = list(slqw);

        return list;
    }

    @Override
    @Transactional
    public void savewithDish(SetMealDto dto) {
        List<SetmealDish> list = dto.getSetmealDishes();
        this.save(dto);

        list.stream().map((item)->{
            item.setSetmealId(dto.getId());
            return item;
        }).collect(Collectors.toList());

        sdService.saveBatch(list);
    }

    @Override
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> slqw = new LambdaQueryWrapper<>();
        slqw.in(Setmeal::getId,ids);
        slqw.eq(Setmeal::getStatus,1);

        int count = count(slqw);
        if (count>0){
            throw new CustomException("套餐有关联菜品,无法删除");
        }

        removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> sdlqw = new LambdaQueryWrapper<>();
        sdlqw.in(SetmealDish::getSetmealId,ids);

        sdService.remove(sdlqw);
    }
}
